package at.ac.tuwien.isis.infret.ue3;

import java.util.Vector;

public class GlobalQueryHandler {
	private Vector<Double[][]> distanceMatrices;
	public GlobalQueryHandler(Vector<Double[][]> distanceMatrices){
		this.distanceMatrices = distanceMatrices;
	}
	
	public Vector<Double[][]> getRankMatrices(){
		Vector<Double[][]> ret = new Vector<Double[][]>();

		
		for(Double[][] matrix :distanceMatrices){
			Double[][] ranks = new Double[matrix.length][matrix.length];
			
			for(int i = 0; i < ranks.length; i++){
				ranks[i] = getRankVector(matrix[i],i);
			}
			ret.add(ranks);
		}
		return ret;
	}
	public Double[][] getMergedRankMatrix(Vector<Double[][]> rankMatrices){
		Double[][] mergedMatrix= new Double[rankMatrices.firstElement().length][rankMatrices.firstElement().length];
		for(Double[][] matrix : rankMatrices){
			for(int i = 0; i < mergedMatrix.length; i ++){
				for(int j = 0 ; j < mergedMatrix.length; j++){
					if(mergedMatrix[i][j] == null)
						mergedMatrix[i][j] = matrix[i][j];
					else
						mergedMatrix[i][j] += matrix[i][j];
				}
			}
		}
		for(int i = 0 ; i < mergedMatrix.length; i++){
			mergedMatrix[i] = getRankVector(mergedMatrix[i],i);
		}
		return mergedMatrix;
	}
	
	public Double[] getRankVector(Double[] distances, int queryIndex){
		Double[] mapping = new Double[distances.length];
		
		for(int i = 0 ; i < mapping.length; i++){
			if(i == queryIndex){
				mapping[i]= Double.NaN;
			}
			Double rankOfI = new Double(i);
			for(int j = i ; j >=0; j --){
				if (j !=queryIndex &&
						distances[i]< distances[j]){
					rankOfI--;
					mapping[j]++;
				}
			}
			mapping[i] = rankOfI;
		}
		return mapping;
	}
}
